﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using XLuaTest;

public static class AutoBind
{

    [MenuItem("AutoBind/Special Command %g")]


    public static void BuildFromUnityMenu()
    {
        string filePath = GetSelectPrefabFilePath();
        Debug.Log(filePath);
        Debug.Log("Start >>>>>");
       
        GameObject selectObject = Selection.activeObject as GameObject;//PrefabUtility.GetCorrespondingObjectFromSource(Selection.activeObject) as GameObject;
        //EditorUtility.GetPrefabParent(Selection.activeObject) as GameObject;
        //GameObject selectObject = AssetDatabase.LoadAssetAtPath(filePath, typeof(GameObject)) as GameObject;
        //GameObject twoCube = PrefabUtility.InstantiatePrefab(twoSphere) as GameObject;


        var compScript = selectObject.GetComponent<CLuaInjectionScriptCom>();
        if(compScript)
        {
            compScript.injections.Clear();
            loopCompChild(selectObject,ref compScript);
        }
        else
        {
            LuaBehaviour luaCom = selectObject.GetComponent<LuaBehaviour>();
            luaCom.injections.Clear();
            foreach (Transform tran in selectObject.transform)
            {
                if (filterObject(tran.name))
                {
                    Injection obj = new Injection();
                    obj.name = tran.name;
                    obj.value = tran.gameObject;
                    luaCom.injections.Add(obj);
                }
            }
        }

      
       
        Debug.Log("Done");
    }


    public static string GetSelectPrefabFilePath()
    {
        Object parentObject = EditorUtility.GetPrefabParent(Selection.activeObject);
        return AssetDatabase.GetAssetPath(parentObject);

    }

    public static bool filterObject(string name)
    {
        if (name.IndexOf("_") == 0)
        {
            return true;

        }
        return false;
    }

    public static void loopCompChild(GameObject loopObj, ref CLuaInjectionScriptCom comScript)
    {
        foreach (Transform child in loopObj.transform)
        {
            if (filterObject(child.name))
            {
                Injection obj = new Injection();
                obj.name = child.name;
                obj.value = child.gameObject;
                comScript.injections.Add(obj);
            }
            loopCompChild(child.gameObject, ref comScript);
        }
    }
}
